package test.nettys.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @Author wangshaopeng
 * @Date 2021/7/28
 */
public class Nio11 {


    public static void main(String[] args) throws IOException {

        ServerSocketChannel channel = ServerSocketChannel.open();
        InetSocketAddress address = new InetSocketAddress(8899);


        channel.socket().bind(address);


        int msgLength = 2 + 3 + 4;

        ByteBuffer[] buffers = new ByteBuffer[3];


        buffers[0] = ByteBuffer.allocate(2);

        buffers[1] = ByteBuffer.allocate(3);

        buffers[2] = ByteBuffer.allocate(4);

        SocketChannel socketChannel = channel.accept();

        while (true){
            int read = 0;
            while (read<msgLength){
                long read1 = socketChannel.read(buffers);
                read += read1;
                System.out.println("byte read "+read1);
                Arrays.stream(buffers).map(b-> "position:"+b.position()+",limit"+b.limit()).forEach(System.out::println);
            }
            Arrays.stream(buffers).forEach(b->{
                b.flip();
            });

            int bytewritten = 0;
            while (bytewritten<msgLength){
                bytewritten += socketChannel.write(buffers);
            }

            Arrays.stream(buffers).forEach(Buffer::clear);
            System.out.println("byteread:" + read + "bytewrite:" + bytewritten);
        }
    }
}
